package com.mzplayer.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;

import com.mzplayer.R;

import java.util.Formatter;
import java.util.Locale;

public class Util {
    private static int SYSTEM_UI = 0;

    /**
     * @return 格式化时间
     */
    public static String stringForTime(long seconds) {
        //int seconds = (int) (timeMS / 1000);
        int minutes = (int) (seconds / 60);
        StringBuilder stringBuilder = new StringBuilder();
        Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
        if (minutes >= 100) {
            return mFormatter.format("%d:%02d:%02d", minutes / 60, minutes % 60, seconds % 60).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds % 60).toString();
        }
    }

    public static String SizeFormat(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format(Locale.CHINA, "%.1fG", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(Locale.CHINA, f > 100 ? "%.0fM" : "%.1fM", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(Locale.CHINA, f > 100 ? "%.0fK" : "%.1fK", f);
        } else {
            return String.format(Locale.CHINA, "%dB", size);
        }
    }

    /**
     * @return 0:获取错误 1:wifi 2:流量
     */
    @SuppressLint("MissingPermission")
    public static int getNetworkType(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (null != connectivity) {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    NetworkCapabilities capabilities = connectivity.getNetworkCapabilities(connectivity.getActiveNetwork());
                    if (capabilities != null) {
                        if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                            return 1;
                        } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                            return 0;
                        }
                    }
                } else {
                    NetworkInfo info = connectivity.getActiveNetworkInfo();
                    if (info != null && info.isConnected()) {
                        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                            return 1;
                        } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                            return 0;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return -1;
    }

    /**
     * @return context转activity
     */
    public static Activity scanForActivity(Context context) {
        if (context instanceof Activity) {
            return (Activity) context;
        } else if (context instanceof ContextWrapper) {
            return scanForActivity(((ContextWrapper) context).getBaseContext());
        }
        return scanForActivity(context);
    }

    /**
     * @param orientation 方向值 0:忽略传感器横屏 1:忽略传感器竖屏 6:传感器横屏
     */
    public static void setScreenOrientation(Context context, int orientation) {
        scanForActivity(context).setRequestedOrientation(orientation);
    }

    /**
     * @return dp对应像素值
     */
    public static int dip2px(Context context, float dpValue) {
        return (int) (context.getResources().getDisplayMetrics().density * dpValue + 0.5f);
    }

    /**
     * @param context context 隐藏虚拟按键 有虚拟键的手机全屏时可隐藏虚拟键 issue:1326
     */
    @SuppressLint("NewApi")
    public static void hideVirtualKey(Context context) {
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            uiOptions |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        }
        View decorView = scanForActivity(context).getWindow().getDecorView();
        SYSTEM_UI = decorView.getSystemUiVisibility();
        decorView.setSystemUiVisibility(uiOptions);
    }

    /**
     * @param context context 显示虚拟按键 有虚拟键的手机全屏时可隐藏虚拟键 issue:1326
     */
    @SuppressLint("NewApi")
    public static void showVirtualKey(Context context) {
        int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
        //Log.e("TAG", "VirtualKey:"+uiOptions);
        scanForActivity(context).getWindow().getDecorView().setSystemUiVisibility(SYSTEM_UI);
    }

    /**
     * @param context context 隐藏状态栏
     */
    public static void hideStatusBar(Context context) {
        scanForActivity(context).getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public static void showStatusBar(Context context) {
        scanForActivity(context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * @return 获取状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }

    /**
     * @return 获取activity的宽高
     */
    public static DisplayMetrics getAppMetrics(Context context) {
        return context.getResources().getDisplayMetrics();
    }

    /**
     * @return 获取屏幕的宽高
     */
    public static DisplayMetrics getScreenMetrics(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        metrics.heightPixels -= getStatusBarHeight(context);
        return metrics;
    }

    /**
     * @return 获取资源id
     */
    public static int getResourcesIndex(Context context, String name, String type) {
        return context.getResources().getIdentifier(name, type, context.getPackageName());
    }

    public static int getResourcesColor(Context context,int index) {
        int color;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            color = context.getColor(index);
        } else {
            color = context.getResources().getColor(index);
        }
        return color;
    }

    //获取NavigationBar的高度
    public static int getNavigationBarHeight(Context context) {
        boolean has = ViewConfiguration.get(context).hasPermanentMenuKey();
        int height;
        return (height = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android")) > 0 && !has ? context.getResources().getDimensionPixelSize(height) : 0;
    }

    public static void hideNavKey(Context context) {
        int uiOptions;
        if (Build.VERSION.SDK_INT >= 29) {
            //       设置屏幕始终在前面，不然点击鼠标，重新出现虚拟按键
            uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav
                    // bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //       设置屏幕始终在前面，不然点击鼠标，重新出现虚拟按键
            uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav
                    // bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
        } else {
            uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; // hide nav
        }
        scanForActivity(context).getWindow().getDecorView().setSystemUiVisibility(uiOptions);
    }

    public static void showNavKey(Context context, int systemUiVisibility) {
        scanForActivity(context).getWindow().getDecorView().setSystemUiVisibility(systemUiVisibility);
    }

    public static int getBrightnessMax() {
        try {
            Resources system = Resources.getSystem();
            int resId = system.getIdentifier("config_screenBrightnessSettingMaximum", "integer", "android");
            if (resId != 0) {
                return system.getInteger(resId);
            }
        } catch (Exception ignore) {
        }
        return 255;
    }

    public static int getBrightness(Context context) {
        float screenBrightness = scanForActivity(context).getWindow().getAttributes().screenBrightness;
        if (screenBrightness >= 0 && screenBrightness <= 1) {
            return (int) (screenBrightness * 255);
        }
        try {
            screenBrightness = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            float brightnessMax = getBrightnessMax();
            if (screenBrightness <= brightnessMax) {
                return (int) (screenBrightness / brightnessMax * 255);
            }
        } catch (Exception ignored) {

        }
        return 125;
    }

    public static void requestFocus(View view) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.requestFocusFromTouch();
    }

    public static void startActivity(Context context, Activity activity) {
        Intent intent = new Intent(context, activity.getClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    private static int touchX;
    private static int touchY;

    public static boolean isClick(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touchX = (int) event.getX();
                touchY = (int) event.getY();
                break;
            case MotionEvent.ACTION_UP:
                if (Math.abs(event.getX() - touchX) < 50 && Math.abs(event.getY() - touchY) < 50) {
                    return true;
                }
                break;
        }
        return false;
    }
    public static View getView(Object obj) {
        if(obj==null) {
            return null;
        }
        if (obj instanceof View) {
            return (View) obj;
        }
        try {
            return (View) obj.getClass().getMethod("getView").invoke(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
